package com.changgou.auth.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity //在web中开启spring security
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        super.configure(auth);
        http.csrf().disable()//禁用跨域请求伪造
                .httpBasic()//开启httpBasic认证
                .and()
                .formLogin()
                .loginPage("/oauth/toLogin")
                .loginProcessingUrl("/oauth/login")//开启登录表单
                .and()
                .authorizeRequests()  //限制认证基于request请求
                .antMatchers("/**")
                .permitAll()
                .anyRequest()
                .authenticated();  //任何请求都需要认证
        //设置用户认证授权对象
        http.userDetailsService(userDetailsService);
    }

    //配置放行一些请求不拦截
    @Override
    public void configure(WebSecurity web) throws Exception {
//        super.configure(web);
        web.ignoring().antMatchers("/oauth/login","/user/**","/oauth/toLogin","/css/**","/data/**","/fonts/**","/img/**","/js/**");
    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManagerBean();
    }
}
